package org.sang.servlet;/*
 * @author  gaokecheng
 * @date 2019/9/9 12:45
 *
 *
 * */

import org.sang.bean.CurrentOnline;
import org.sang.bean.Hr;
import org.sang.common.FinalString;
import org.sang.common.HrUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@WebListener
public class OnLineCount implements HttpSessionListener {
    private final org.slf4j.Logger log = LoggerFactory.getLogger(getClass());


    @Autowired
    private RedisTemplate redisTemplate;
    public int current_count = 0;//记录session的数量
    public String tag;

    @Override
    //监听session的创建,synchronized 防并发bug
    public synchronized void sessionCreated(HttpSessionEvent se) {
        /*Hr user = (Hr) securityContextHolder.getContext().getAuthentication().getPrincipal();*/
        if (redisTemplate.hasKey(FinalString.CURRENT_COUNT)) {
            current_count = (int) redisTemplate.opsForValue().get(FinalString.CURRENT_COUNT);
            current_count++;
        } else {
            current_count++;
        }
        redisTemplate.opsForValue().set(FinalString.CURRENT_COUNT, current_count);


    }

    @Override
    public synchronized void sessionDestroyed(HttpSessionEvent arg0) {
        if (current_count > 0) {
            current_count--;
        } else {
            current_count = 0;
        }
        redisTemplate.opsForValue().set(FinalString.CURRENT_COUNT, current_count);

    }

}
